import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
	state: {
		openid: void 0,
		userInfo: null,
		cart: [],
	},
	mutations: {
		saveOpenid(state, options) {
			state.openid = options;
		},
		saveUserInfo(state, options) {
			state.userInfo = options;
		},
		addCart(state, options) {
			if (state.cart.length === 0) {
				state.cart.push(options);
				uni.showToast({
					title: `成功添加购物车了`,
					icon: "success",
					duration: 0.8 * 1000
				});
				return;
			};
			let isAdd = state.cart.filter((value, index, arr) => {
				return value.id === options.id;
			});
			if (!isAdd.length) {
				state.cart.push(options);
				uni.showToast({
					title: `成功添加购物车了`,
					icon: "success",
					duration: 0.8 * 1000
				});
			} else {
				uni.showToast({
					title: `已经添加过购物车了`,
					icon: "none",
					duration: 0.8 * 1000
				});
			};
		},
		delCart(state, options) {
			state.cart.splice(options, 1);
			this.commit("setTabBar");
		},
		setTabBar(state) {
			let num = state.cart.length;
			if (num > 0) {
				uni.setTabBarBadge({
					index: 3,
					text: `${num}`
				});
			} else {
				uni.removeTabBarBadge({
					index: 3
				});
			};
		},
	},
	actions: {},
	getters: {},
})
export default store;
